<!-- 基线用例模块 -->
<template>
  <div class="div_box">
    <div style="min-width: 1600px;">
      <el-row>
        <el-form ref="form" :inline="true" label-width="100px">
          <el-col :span="4">
            <el-form-item label="">
              <el-button-group>
                <el-button type="primary" size="small" icon="el-icon-upload" title="上传用例文件" @click="caseUpload" />
                <el-button type="primary" size="small" icon="el-icon-delete-solid" title="删除用例" @click="trueDelete" />
              </el-button-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-select v-model="selectMouldeList" multiple collapse-tags filterable style="margin-left: 20px; width: 100%;" placeholder="选择模块">
              <el-option v-for="item in selectModuleListOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
        </el-form>
      </el-row>
      <div class="div_box">
        <div class="components-container">
          <split-pane :min-percent="15" :default-percent="15" split="vertical">
            <!-- 页面布局：中部·左 -->
            <!-- 用例树 -->
            <template slot="paneL">
              <div class="left-container">
                <el-tree
                  ref="caseTreeRef"
                  :data="caseTreeData"
                  :props="defaultProps"
                  node-key="id"
                  :default-expanded-keys="defaultExpandedKeys"
                  :default-expand-all="defaultExpandAll"
                  :filter-node-method="filterNode"
                  :highlight-current="true"
                  show-checkbox
                  :draggable="draggable"
                  :allow-drop="allowDrop"
                  :allow-drag="allowDrag"
                  @node-click="handleCaseNodeClick"
                  @node-drag-start="handleDragStart"
                  @node-drag-end="handleDragEnd"
                  @node-expand="handleCaseNodeExpend"
                  @node-collapse="handleCaseNodeCollapse"
                  @node-contextmenu="rightClick"
                >
                  <span slot-scope="{ node, data }" class="custom-case-tree" style="width: 100%;">
                    <span :title="data.title">
                      <svg-icon :icon-class="node.data.icon" />
                      <span :title="node.data.label" style="font-size: 14px;">{{ node.data.label }}</span>
                    </span>
                  </span>
                </el-tree>
              </div>
            </template>
            <!-- 页面布局：中部·右 -->
            <template slot="paneR">
              <div class="right-container">
                <!-- 内部宽度固定 -->
                <div style="width: 1200px;">
                  <!-- 文件夹详情 -->
                  <div v-if="rightView == 1" id="case-folder">
                    <el-form ref="creatorForm" :model="creatorForm" label-width="80px">
                      <el-row :gutter="20">
                        <el-col :span="10">
                          <el-form-item label="用例编号">
                            <el-input v-model="creatorForm.caseNum" placeholder="在所有用例中全局唯一，提交时校验。" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="5">
                          <el-form-item label="自动化">
                            <el-radio-group v-model="creatorForm.auto">
                              <el-radio :label="1">是</el-radio>
                              <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                          </el-form-item>
                        </el-col>
                        <el-col :span="4">
                          <el-form-item label="级别">
                            <el-select v-model="creatorForm.caseLevel" placeholder="请选择">
                              <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="5">
                          <el-form-item label="关联模块">
                            <el-select v-model="creatorForm.moduleList" multiple filterable allow-create default-first-option placeholder="请选择模块标签">
                              <el-option v-for="item in selectModuleListOption" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="用例名称">
                            <el-input v-model="creatorForm.caseName" placeholder="请输入内容" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="用例描述">
                            <el-input v-model="creatorForm.caseDesc" placeholder="请输入内容" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="预置条件" prop="desc">
                            <el-input v-model="creatorForm.beforeTest" type="textarea" placeholder="请输入内容" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="测试步骤" prop="desc">
                            <el-input v-model="creatorForm.onTest" type="textarea" placeholder="请输入内容" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="后置操作" prop="desc">
                            <el-input v-model="creatorForm.afterTest" type="textarea" placeholder="请输入内容" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="预期结果" prop="desc">
                            <el-input v-model="creatorForm.expect" type="textarea" placeholder="请输入内容" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item>
                            <el-button type="primary" @click="createrOnA()">创建同级目录添加用例</el-button>
                            <el-button type="primary" @click="createrOnB()">创建子目录添加用例</el-button>
                            <el-button type="primary" @click="createrOnC()">仅创建用例</el-button>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                  </div>
                  <!-- 用例详情 -->
                  <div v-if="rightView == 2" id="case-detail">
                    <el-form ref="caseForm" :model="caseForm" label-width="80px">
                      <el-row :gutter="20">
                        <el-col :span="16">
                          <el-form-item label="用例编号">
                            <el-input v-model="caseForm.caseNum" :disabled="true" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="4">
                          <el-form-item label="级别">
                            <el-select v-model="caseForm.caseLevel" placeholder="请选择">
                              <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="4">
                          <el-form-item label="结果">
                            <el-tag v-if="caseForm.lastResult === 1" type="success">已通过</el-tag>
                            <el-tag v-if="caseForm.lastResult === 0" type="info">未执行</el-tag>
                            <el-tag v-if="caseForm.lastResult === 3" type="warning">阻塞中</el-tag>
                            <el-tag v-if="caseForm.lastResult === 2" type="danger">已失败</el-tag>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="18">
                          <el-form-item label="用例名称">
                            <el-input v-model="caseForm.caseName" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="自动化">
                            <el-radio-group v-model="caseForm.auto">
                              <el-radio :label="1">是</el-radio>
                              <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="用例描述">
                            <el-input v-model="caseForm.caseDetail.caseDesc" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="6">
                          <el-form-item label="创建人">
                            <el-input v-model="caseForm.author" :disabled="true" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="更新时间">
                            <el-input v-model="caseForm.modifyTime" :disabled="true" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item label="关联模块">
                            <el-select v-model="caseFormModuleList" multiple filterable allow-create default-first-option placeholder="请选择模块标签">
                              <el-option v-for="item in selectModuleListOption" :key="item.label" :label="item.label" :value="item.label" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <!-- <el-col :span="6">
                              <el-form-item label="相关BUG">
                                <el-input v-model="caseForm.bugs" placeholder="暂未使用" :disabled="true" />
                              </el-form-item>
                            </el-col> -->
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="预置条件" prop="desc">
                            <el-input v-model="caseForm.caseDetail.beforeTest" type="textarea" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="测试步骤" prop="desc">
                            <el-input v-model="caseForm.caseDetail.onTest" type="textarea" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="后置操作" prop="desc">
                            <el-input v-model="caseForm.caseDetail.afterTest" type="textarea" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="24">
                          <el-form-item label="预期结果" prop="desc">
                            <el-input v-model="caseForm.caseDetail.expect" type="textarea" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-form-item>
                          <el-button type="primary" @click="updateModify()">提交修改</el-button>
                          <el-button type="primary" @click="editScript(caseForm.id)">编辑脚本</el-button>
                          <el-button type="primary" @click="todo('caseForm')">执行脚本</el-button>
                          <el-button type="primary" @click="showHistory(caseForm.execInfo)">历史结果</el-button>
                        </el-form-item>
                      </el-row>
                    </el-form>
                  </div>
                </div>
              </div>
            </template>
          </split-pane>
        </div>
      </div>
      <!-- 用例历史，模态框 -->
      <caseHistory ref="caseHistory" />
      <caseUpload ref="caseUpload" @reflushDataList="getCaseTree()" />
    </div>
  </div>
</template>

<script>
import CaseHistory from './case-list-history'
import CaseUpload from './case-list-upload'
import splitPane from 'vue-splitpane'
import { findAllModules } from '@/api/auto/module.js'
import { moduleCaseTree, updateTree, searchDetail, updateCase } from '@/api/auto/case.js'
export default {
  name: 'AutoCaseProduct',
  components: {
    splitPane,
    CaseHistory,
    CaseUpload
  },
  data() {
    return {
      selectMouldeList: [],
      selectModuleListOption: [],
      caseTreeData: [{ id: 0, label: '用例列表', icon: 'love-flowers', children: [], root: true }], // 前端页面上的根节点
      defaultProps: { children: 'children', label: 'label' },
      defaultExpandedKeys: [0], // 默认展开节点
      defaultExpandAll: true,
      draggable: true,
      caseTreeLoading: false,
      rightView: 0,
      creatorForm: { auto: 0, caseLevel: 1 },
      caseForm: {},
      levelOptions: [
        { value: 1, label: 'Level1' },
        { value: 2, label: 'Level2' },
        { value: 3, label: 'Level3' },
        { value: 4, label: 'Level4' },
        { value: 5, label: 'Level5' }
      ],
      caseFormModuleList: []
    }
  },
  watch: {
    selectMouldeList(newValue, oldValue) {
      this.getCaseTree()
    }
  },
  created() {
    this.init()
  },
  activated() {
    this.init()
  },
  methods: {
    todo() {
      this.$message('todo')
    },
    init() {
      findAllModules().then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.selectModuleListOption = data
        } else {
          this.$message.error(respnose.message)
          this.selectModuleListOption = []
        }
      })
      this.getCaseTree()
    },
    getCaseTree() {
      this.caseTreeLoading = true
      moduleCaseTree(this.selectMouldeList.join(',')).then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.caseTreeData[0].children = data
        } else {
          this.$message.error(respnose.message)
          this.caseTreeData[0].children = []
        }
        this.caseTreeLoading = false
      })
    },
    caseUpload() {
      /**
       * 上传用例，打开是一个弹窗
       * -1 代表不走需求上传，无需关联需求
       */
      this.$nextTick(() => {
        this.$refs.caseUpload.init(-1)
      })
    },
    trueDelete() {
      this.$message.warning('暂时不支持删除~')
    },
    filterNode(value, data, node) {
      /**
       * 过滤用例树，根据结果、名称、用例编号等筛选功能会触发这里
       */
      if (this.selectCheckList.length === 0) {
        return true
      }
      var i = 0
      if (!data.isCaseNode) {
        for (i = 0; i < this.selectCheckList.length; i++) {
          if (JSON.stringify(data.children).indexOf('"icon":' + this.selectCheckList[i]) !== -1) {
            return true
          }
        }
        return false
      }
      for (i = 0; i < this.selectCheckList.length; i++) {
        if (data.icon === this.selectCheckList[i]) {
          this.defaultExpandedKeys.push(data.id)
          node.checked = true
          return true
        }
      }
      node.checked = false
      return false
    },
    // 是否允许放下
    allowDrop(draggingNode, dropNode, type) {
      // 最上面的节点不允许拖拽放置
      if (dropNode.data.label === '用例列表') {
        return false
      }
      // return !dropNode.data.isCaseNode
      return true
    },
    // 是否允许托起
    allowDrag(draggingNode) {
      // 最上面的节点不允许拖拽放置
      if (draggingNode.data.label === '用例列表') {
        return false
      }
      return true
    },
    handleCaseNodeClick(data) {
      /**
       * 点击用例，查询用例详情
       */
      if (data.isCaseNode) {
        // 第二个参数1，代表查询的是模块用例结果，第三个参数这种情况下没用
        searchDetail(data.id, 1, 0).then(respnose => {
          if (respnose && respnose.code === 200) {
            const { data } = respnose
            this.caseForm = data
            this.caseFormModuleList.length = 0
            const modules = this.caseForm.modules.split('、')
            for (var i = 0; i < modules.length; i++) {
              this.caseFormModuleList.push(modules[i])
            }
          } else {
            this.$message.error(respnose.message)
          }
          this.rightView = 2
        })
      } else {
        this.rightView = 1
        this.creatorForm = {}
        this.creatorForm.folderId = -data.id
      }
    },
    handleDragStart(node, ev) {
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      /**
       * 控制用例结构移动的核心方法
       */
      var caseFolderSortS = []
      var caseDetailSortS = []
      var brotherNodes = dropType === 'inner' ? dropNode.childNodes : dropNode.parent.childNodes

      for (var i = 0; i < brotherNodes.length; i++) {
        brotherNodes[i].data.isCaseNode ? caseDetailSortS.push(brotherNodes[i].data.id) : caseFolderSortS.push(brotherNodes[i].data.id)
      }

      this.caseTreeLoading = true
      updateTree(
        draggingNode.data.id,
        dropNode.data.id,
        draggingNode.data.isCaseNode ? 1 : 0,
        dropNode.data.isCaseNode ? 1 : 0,
        dropType,
        caseFolderSortS.join(','),
        caseDetailSortS.join(',')
      ).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
        } else {
          this.$message.error(respnose.message)
        }
        this.getCaseTree()
      })
    },
    handleCaseNodeExpend(data) {
      /**
       * 节点展开，图标切换
       */
      this.defaultExpandedKeys.push(data.id)
      // 根节点是一朵花
      if (data.root) { return }
      data.icon = 'folder-open'
    },
    handleCaseNodeCollapse(data) {
      /**
       * 节点关闭，图标切换
       */
      this.defaultExpandedKeys.splice(this.defaultExpandedKeys.indexOf(data.id), 1)
      // 根节点是一朵花
      if (data.root) { return }
      data.icon = 'folder-close'
    },
    rightClick(event, data, node, obj) {
    },
    updateModify() {
      /**
       * 编辑用例信息，保存
       */
      this.$prompt('说明修改了那些东西，留做记录', '请填写原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (!value || value === '') {
          this.caseForm.remark = 'NA'
        } else {
          this.caseForm.remark = value
        }
        this.caseForm.modules = this.caseFormModuleList.join('、')
        console.info(this.caseForm)
        updateCase(this.caseForm).then(respnose => {
          if (respnose && respnose.code === 200) {
            const { data } = respnose
            this.caseForm = data
            this.caseFormModuleList.length = 0
            const modules = this.caseForm.modules.split('、')
            for (var i = 0; i < modules.length; i++) {
              this.caseFormModuleList.push(modules[i])
            }
            this.$message.success(respnose.message)
          } else {
            this.$message.error(respnose.message)
          }
        })
      }).catch(() => {
      })
    },
    editScript(id) {
      /**
       * 编辑脚本，跳转到一个新页面处理
       */
      // 这里不要删除缓存了
      // this.$store.dispatch('tagsView/delView', { name: 'AutoCaseScript', path: '/auto/auto-case-script' })
      this.$nextTick(() => {
        this.$router.push({
          name: 'AutoCaseScript',
          params: {
            caseId: id
          }
        })
      })
    },
    showHistory(execInfo) {
      /**
       * 查询用例历史执行结果，显示在一个弹窗里面
       */
      this.$nextTick(() => {
        this.$refs.caseHistory.init(execInfo)
      })
    }
  }
}
</script>

<style scoped="scoped">
.div_box {
  border: 1px solid #eee;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 15px;
  padding-bottom: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
}

.components-container {
  position: relative;
  height: 75vh;
  margin: 0;
}

.case-spilt-div {
  background: #FFFFFF;
  border:1px solid #eeeeee;
  margin: 10px 10px 10px 10px;
}

.left-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
  padding: 10px 20px;
}

.right-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
  padding: 10px 20px;
}
</style>
